//
// $Id$
//
// The server agent for Codename_Maximum - an AVR game for Whirled

package
{

	import com.whirled.ServerObject;
	import com.whirled.game.GameControl;
	import com.whirled.net.MessageReceivedEvent;
	import com.whirled.net.PropertyChangedEvent;
	import com.whirled.avrg.AVRServerGameControl;
	import com.whirled.avrg.RoomSubControlServer;
	import com.whirled.avrg.*;
	import aduros.net.*;
	import aduros.util.F;

	import flash.utils.Dictionary;
	import flash.utils.getTimer;

	import com.threerings.util.Log;
	import com.threerings.util.MethodQueue;

	/**
	 * The server agent for Codename_Maximum. Automatically created by the 
	 * whirled server whenever a new game is started. 
	 */
	public class Server extends ServerObject
	{
		/**
		     * Constructs a new server agent.
		     */
		public function Server()
		{
			_control = new AVRServerGameControl(this);
			new RemoteProvider(_control.game,"s",F.konst(this));
			_gameReceiver = new RemoteCaller(_control.game,"c");

			_invoker = new BatchInvoker(_control);
			_invoker.start(500);

			_control.game.addEventListener(AVRGameControlEvent.PLAYER_JOINED_GAME,doSomething);
			//_control.game.addEventListener(AVRGameControlEvent.PLAYER_QUIT_GAME, handlePlayerQuit);


			function doSomething(event:AVRGameControlEvent):void
			{
				var player:PlayerSubControlServer = _control.getPlayer(event.value as int);
				var room:RoomSubControlServer = _control.getRoom(event.value as int);
				feed(player.getPlayerName() + " has logged on to C:M. \n" + "http://www.whirled.com/#people-" + player.getPlayerId());

				/*if ( ! player.holdsTrophy ("beta_tester")){
				player.awardTrophy ("beta_tester");
				feed(player.getPlayerName()+ " has won the Beta Tester trophy! \n" );
				}*/


			}

		}


		protected function feed(text:String):void
		{
			_gameReceiver.apply("feed",text);
		}

		protected function getPlayerName(playerId:int):String
		{
			return _control.getPlayer(playerId).getPlayerName();
		}

		REMOTE function broadcast(playerId:int,message:Array):void
		{
			_invoker.push(F.callback(_gameReceiver.apply,"broadcast",[getPlayerName(playerId)].concat(message)));
		}




		protected var _gameReceiver:RemoteCaller;
		protected var _control:AVRServerGameControl;
		protected var _invoker:BatchInvoker;
	}

}